<template>
  <div class="home">
    <div class="user">
      <el-dropdown placement="bottom-start" trigger="click">
        <span class="el-dropdown-link">
          {{userName}}<el-icon class="el-icon--right"><arrow-down /></el-icon>
        </span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="updatePassword">修改密码</el-dropdown-item>
            <el-dropdown-item @click="logout">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
    <el-tabs type="border-card" v-model="activeName" @tab-change="onTabChange">
      <el-tab-pane label="订单列表" name="order">
        <div class="search">
          <el-form :inline="true" :model="orderParams" class="demo-form-inline">
            <el-form-item label="保温柜名称:">
              <el-select style="width: 160px;" clearable v-model="orderParams.cabinetName" placeholder="请选择">
                <el-option v-for="(item,index) in cabinetsList" :key="index" :label="item.name" :value="item.name" />
              </el-select>
            </el-form-item>
            <el-form-item label="商铺:">
              <el-select style="width: 160px;" v-model="orderParams.storeCode" placeholder="请选择">
                <el-option v-for="(item,index) in storeList" :key="index" :label="item.name" :value="item.code" />
              </el-select>
            </el-form-item>
            <el-form-item label="订单类型:">
              <el-select style="width: 160px;" v-model="orderParams.type" placeholder="请选择">
                <el-option label="全部" value="0" />
                <el-option label="保温柜订单" value="1" />
                <el-option label="自取订单" value="2" />
              </el-select>
            </el-form-item>
            <el-form-item label="订餐类型:">
              <el-select style="width: 160px;" v-model="orderParams.category" placeholder="请选择">
                <el-option label="早餐" value="1" />
                <el-option label="午餐" value="2" />
                <el-option label="晚餐" value="3" />
              </el-select>
            </el-form-item>
            <el-form-item label="订单日期:">
              <el-date-picker
                v-model="orderParams.date"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择日期"
                clearable
              />
            </el-form-item>
            <el-form-item label="时间:">
              <el-time-picker
                v-model="orderParams.time"
                placeholder="请选择时间"
                value-format="HH:mm:ss"
                clearable
              />
            </el-form-item>
            <el-form-item label="订单号:">
              <el-input style="width: 160px;" v-model="orderParams.orderNo" placeholder="请输入订单号" clearable />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="getOrderList">查询</el-button>
              <el-button type="primary" @click="exportTable">导出</el-button>
              <el-button type="primary" @click="printTable">打印</el-button>
            </el-form-item>
            <el-form-item>
              <div style="font-size: 18px;">
                订单总量：
                <span style="font-weight: bold;">{{ tableData.length || 0 }}</span>
              </div> 
            </el-form-item>
          </el-form>
        </div>
        <div class="table orderTable">
          <el-table :data="tableData" default-expand-all height="100%"  :header-cell-style="{color:'#000' }" border empty-text="暂无数据" style="width: 100%">
            <el-table-column type="expand" width="100">
              <template #default="props">
                <div m="4" class="expandTable">
                  <el-table :data="props.row.goodsList" :border="true" :header-cell-style="{background:'#f1f1f1',color:'#333333'}" :cell-style="{background:'#ffffff'}" empty-text="暂无数据" stripe>
                    <el-table-column label="餐品id" align="center" prop="id" />
                    <el-table-column label="餐品名称" align="center" prop="name" />
                    <el-table-column label="数量" align="center" prop="num" />
                    <el-table-column label="商铺地址" align="center" prop="store" />
                    <el-table-column label="商铺编码" align="center" prop="storeCode" />
                  </el-table>
                </div>
              </template>
            </el-table-column>
            <el-table-column type="index" width="100" align="center" label="序号" />
            <el-table-column prop="orderNo" align="center" label="订单号" />
            <el-table-column prop="phonenumber" align="center" label="手机号" >
              <template #default="scope">
                {{ scope.row.phonenumber }}
                <el-icon v-if="scope.row.phonenumber" style="margin-left: 4px; cursor: pointer" @click="clickCopy(scope.row.phonenumber)"><DocumentCopy /></el-icon>
              </template>
            </el-table-column>
            <el-table-column prop="cabinetPickupCode" align="center" label="取餐码">
              <template #default="scope">
                {{ scope.row.cabinetName }}-{{ scope.row.cabinetPickupCode }}
              </template>
            </el-table-column>
            <el-table-column prop="createTime" align="center" label="订单时间" />
            <!-- totalAmount -->
            <el-table-column prop="totalAmount" align="center" label="订单金额" />
            <!-- 操作  -->
            <el-table-column label="操作" align="center" width="100" v-if="userInfo.isAdmin">
              <template #default="scope">
                <el-button type="text" size="small" @click="refundClick(scope.row)">退款</el-button>
                </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
      <el-tab-pane label="菜品销量" name="goods">
        <div class="search">
          <el-form :inline="true" :model="orderParams" class="demo-form-inline">
            <el-form-item label="日期:">
              <el-date-picker
                v-model="goodsParams.date"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择日期"
                clearable
              />
            </el-form-item>
            <el-form-item label="时间:">
              <el-time-picker
                v-model="goodsParams.time"
                placeholder="请选择时间"
                value-format="HH:mm:ss"
                clearable
              />
            </el-form-item>
            <el-form-item label="订餐类型:">
              <el-select style="width: 160px;" v-model="goodsParams.category" placeholder="请选择">
                <el-option label="早餐" value="1" />
                <el-option label="午餐" value="2" />
                <el-option label="晚餐" value="3" />
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="商铺编码:">
              <el-input v-model="goodsParams.storeCode" placeholder="请输入" clearable />
            </el-form-item> -->
            <el-form-item label="商铺:">
              <el-select style="width: 160px;" v-model="goodsParams.storeCode" placeholder="请选择">
                <el-option v-for="(item,index) in storeList" :key="index" :label="item.name" :value="item.code" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="getGoodsList">查询</el-button>
              <el-button type="primary" @click="exportGoodsList">导出</el-button>
            </el-form-item>
            <el-form-item>
              <div style="font-size: 18px;">
                流水：
                <span style="font-weight: bold;">{{ total.toFixed(2) || 0 }}</span>
              </div> 
            </el-form-item>
            <el-form-item>
              <div style="font-size: 18px;">
                成本：
                <span style="font-weight: bold;">{{ (total*(1 - sharingRatio)).toFixed(2) || 0 }}</span>
              </div> 
            </el-form-item>
            <el-form-item>
              <div style="font-size: 18px;">
                盈利：
                <span style="font-weight: bold;">{{ (total* sharingRatio).toFixed(2) || 0 }}</span>
              </div> 
            </el-form-item>
          </el-form>
        </div>
        <div class="table">
          <el-table :data="goodsSaleData" :summary-method="getSummaries"
    show-summary :header-cell-style="{color:'#000',background: '#EEF5FE' }" height="100%" border empty-text="暂无数据" stripe>
            <el-table-column label="餐品id" align="center" prop="goodsId" />
            <el-table-column label="餐品名称" align="center" prop="goodsName" />
            <el-table-column label="销量" align="center" sortable prop="sales" />
            <el-table-column label="商铺名称" align="center" prop="storeName" />
            <el-table-column label="商铺编码" align="center" prop="storeCode" />
            <el-table-column label="金额" align="center" prop="amount" />
          </el-table>
        </div>
      </el-tab-pane>
      <el-tab-pane v-if="userInfo.isAdmin" label="保温柜数量统计" name="cabinets">
        <div class="search">
          <el-form :inline="true" :model="cabinetsNumParams" class="demo-form-inline">
            <el-form-item label="订餐类型:">
              <el-select style="width: 160px;" v-model="cabinetsNumParams.category" placeholder="请选择">
                <el-option label="早餐" value="1" />
                <el-option label="午餐" value="2" />
                <el-option label="晚餐" value="3" />
              </el-select>
            </el-form-item>
            <el-form-item label="订单日期:">
              <el-date-picker
                v-model="cabinetsNumParams.date"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择日期"
                clearable
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="getCabinetsNum">查询</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="table">
          <el-table :data="cabinetsNumTable" :summary-method="getSummaries1"
    show-summary  :header-cell-style="{color:'#000',background: '#EEF5FE' }" height="100%" border empty-text="暂无数据" stripe>
            <el-table-column label="保温柜名称" align="center" prop="cabinetName" />
            <el-table-column label="订单数量" sortable align="center" prop="value" />
          </el-table>
        </div>
      </el-tab-pane>
      <el-tab-pane v-if="userInfo.isAdmin" label="短信通知" name="notice">
        <el-form :inline="true" :model="noticeParams" class="demo-form-inline">
          <el-form-item label="类型:">
            <el-select style="width: 160px;" v-model="noticeParams.type" placeholder="请选择">
              <el-option label="早餐" value="1" />
              <el-option label="午餐" value="2" />
              <el-option label="晚餐" value="3" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="sendNotice">发送短信</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane v-if="userInfo.isAdmin" label="导出取件码" name="code">
        <el-form :inline="true" :model="exportParams" class="demo-form-inline">
          <el-form-item label="类型:">
            <el-select style="width: 160px;" v-model="exportParams.category" placeholder="请选择">
              <el-option label="早餐" value="1" />
              <el-option label="午餐" value="2" />
              <el-option label="晚餐" value="3" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="exportCodeFn">导出取件码</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane v-if="userInfo.isAdmin" label="用户列表" name="user">
        <div class="add">
          <el-button type="primary" @click="addUser">新增</el-button>
        </div>
        <div class="table">
          <el-table :data="userList" :header-cell-style="{color:'#000',background: '#EEF5FE' }" height="100%" border empty-text="暂无数据" stripe>
            <el-table-column label="用户ID" align="center" prop="userId" />
            <el-table-column label="手机号" sortable align="center" prop="userName" />
            <el-table-column label="用户名" sortable align="center" prop="nickName" />
            <el-table-column label="角色" align="center">
              <template #default="{row}">
                <span v-if="row.userType==1">管理员</span>
                <span v-else>普通用户</span>
              </template>
            </el-table-column>
            <el-table-column label="关联商户" align="center">
              <template #default="{row}">
                <span>{{getStore(row.storeCode)}}</span>
              </template>
            </el-table-column>
            <el-table-column label="状态" align="center">
              <template #default="{row}">
                <span v-if="row.status==1">停用</span>
                <span v-if="row.status==0">正常</span>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" sortable align="center" prop="createTime" />
            <el-table-column label="操作" align="center">
              <template #default="{row}">
                <el-button type="text" @click="editUser(row)">编辑</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>

      <el-tab-pane v-if="userInfo.isAdmin" label="反馈列表" name="feedback">
        <feedback :dataList="feedbackList"></feedback>
      </el-tab-pane>
      <el-tab-pane v-if="userInfo.isAdmin" label="商品管理" name="goodsList">
        <goods :dataList="goodsList" :storeList="allStoreList" :categoryList="categoryList"></goods>
      </el-tab-pane>
      <el-tab-pane v-if="userInfo.isAdmin" label="拼团商品" name="ptGoodsList">
        <ptGoods :dataList="ptGoodsList"></ptGoods>
      </el-tab-pane>
      <el-tab-pane v-if="userInfo.isAdmin" label="团购订单列表" name="ptOrder">
        <ptOrder :dataList="tableDataPt" :ptGoodsList="ptGoodsList"></ptOrder>
      </el-tab-pane>
      <el-tab-pane label="本周菜单" name="weekMenu">
        <weekMenu :dataList="menuList" :goodsList="goodsList" :storeList="allStoreList"></weekMenu>
      </el-tab-pane>

      <!-- 定时任务管理 -->
      <el-tab-pane v-if="userInfo.isAdmin" label="定时任务管理" name="cron">
        <cron :dataList="cronList"></cron>
      </el-tab-pane>

    </el-tabs>

    <el-dialog :close-on-click-modal="false" v-model="dialogFormVisible" :title="dialogType=='add'?'新增':'编辑'">
      <el-form ref="ruleFormRef" :model="userForm" :rules="rules">
        <el-form-item prop="mobile" label="手机号" :label-width="formLabelWidth">
          <el-input v-model="userForm.mobile" autocomplete="off" placeholder=" 请输入手机号" />
        </el-form-item>
        <el-form-item v-if="dialogType=='add'" prop="password" label="密码" :label-width="formLabelWidth">
          <el-input v-model="userForm.password" autocomplete="off" placeholder="请输入密码" />
        </el-form-item>
         <el-form-item v-if="dialogType=='edit'" label="修改密码" :label-width="formLabelWidth">
          <el-input v-model="userForm.password" autocomplete="off" placeholder="请输入修改密码（不填则是旧密码）" />
        </el-form-item>
        <el-form-item prop="userType" label="角色" :label-width="formLabelWidth">
          <el-select v-model="userForm.userType" placeholder="请选择角色">
            <el-option label="普通用户" value="0" />
            <el-option label="管理员" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item prop="storeCode" label="关联商铺" :label-width="formLabelWidth">
          <el-select multiple v-model="userForm.storeCode" placeholder="请选择商铺">
            <el-option v-for="(item,index) in allStoreList" :key="index" :label="item.name" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item label="昵称" :label-width="formLabelWidth">
          <el-input v-model="userForm.nickName" autocomplete="off" placeholder="请输入昵称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">关闭</el-button>
          <el-button type="primary" @click="submitAddUser(ruleFormRef)">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :close-on-click-modal="false" v-model="dialogPassVisible" title="修改密码">
      <el-form ref="rulePassRef" :model="passForm" :rules="passrules">
        <el-form-item prop="password" label="旧密码" :label-width="formLabelWidth">
          <el-input v-model="passForm.password" autocomplete="off" placeholder="请输入旧密码" />
        </el-form-item>
         <el-form-item prop="newPassword" label="新密码" :label-width="formLabelWidth">
          <el-input v-model="passForm.newPassword" autocomplete="off" placeholder="请输入新密码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogPassVisible = false">关闭</el-button>
          <el-button type="primary" @click="submitUpdatePass(rulePassRef)">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :close-on-click-modal="false" v-model="refundVisible" title="退款">
      <el-form ref="ruleRefundRef" :model="refundForm" :rules="refundrules">
        <el-form-item prop="orderNo" label="订单号" :label-width="formLabelWidth">
          <el-input readonly v-model="refundForm.orderNo" autocomplete="off" placeholder="请输入订单号" />
        </el-form-item>
        <el-form-item prop="totalAmount" label="退款金额" :label-width="formLabelWidth">
          <el-input type="number" v-model="refundForm.totalAmount" autocomplete="off" placeholder="请输入退款金额" />
        </el-form-item>
        <el-form-item prop="remark" label="退款原因" :label-width="formLabelWidth">
          <el-input type="textarea" :rows="4" v-model="refundForm.remark" autocomplete="off" placeholder="请输入退款原因" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="refundVisible = false">关闭</el-button>
          <el-button type="primary" @click="submitRefund(ruleRefundRef)">确定</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script>
import { onMounted,reactive,ref,computed } from "vue";
import { getOrderData,getGoodsData,orderRefundData,getMenuListData,getCronListData,getOrderExport,getPtList,getCategoryList,getGoodsList,getPtGoodsList,getFeedbackList,getUserList,getGoodsExport,getSendData,exportCode,getStoreData,printCode,getCabinetData,addUserData,updatePasswordData } from '@/api/home.js'
import { ElMessage,ElMessageBox } from 'element-plus'
import { useRouter } from "vue-router";
import feedback from './component/feedback.vue'
import goods from './component/goods.vue'
import ptGoods from './component/ptGoods.vue'
import ptOrder from './component/ptOrder.vue'
import weekMenu from './component/weekMenu.vue'
import cron from './component/cron.vue'
export default {
  components: { feedback,goods,ptGoods,ptOrder,weekMenu,cron },
  setup() {
    const router = useRouter();
    const total = ref(0)
    const sharingRatio = ref(0)
    const ruleFormRef = ref()
    const rulePassRef = ref()
    const ruleRefundRef = ref()
    
    let dialogFormVisible = ref(false)
    let dialogType = ref('add')
    let dialogPassVisible = ref(false)
    let refundVisible = ref(false)
    
    let userForm = ref({
      mobile:"",
      password:"",
      userType:"",
      storeCode:[],
      nickName:"",  
    })

    let passForm = ref({
      password:"",
      newPassword:"",
      userId:JSON.parse(localStorage.getItem('yxUserInfo')).userId || "",
    })
    let refundForm = ref({
      orderNo:"",
      totalAmount:"",
      remark:"",
    })
    const data = reactive({
      formLabelWidth:"120px",
      feedbackList:[],
      goodsList:[],
      ptGoodsList:[],
      categoryList:[],
      userName: localStorage.getItem('yxUserName') || "",
      rules: {
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6,max: 15,message: '长度在 6 到 15 个字符',trigger: 'blur'}
        ],
        userType: [
          { required: true, message: '请选择角色', trigger: 'blur' },
        ],
        storeCode: [
          { required: true, message: '请选择关联商铺', trigger: 'blur' },
        ],
      },
      passrules:{
        password: [
          { required: true, message: '请输入旧密码', trigger: 'blur' },
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6,max: 15,message: '长度在 6 到 15 个字符',trigger: 'blur'}
        ],
      },
      refundrules:{
        orderNo: [
          { required: true, message: '请输入订单号', trigger: 'blur' },
        ],
        totalAmount: [
          { required: true, message: '请输入退款金额', trigger: 'blur' },
        ],
        remark:[
          { required: true, message: '请输入退款原因', trigger: 'blur' },
        ]
      },
      userInfo: JSON.parse(localStorage.getItem('yxUserInfo')) || {},
      orderParams:{
        date:"",
        time:"",
        type:"1",
        storeName:"",
        storeCode:"",
        category:"2",
        orderNo:"",
      },
      activeName:"order",
      goodsParams:{
        date:"",
        storeCode:"",
        time:"",
        category:"2"
      },
      cabinetsNumParams:{
        date:"",
        time:"",
        type:"",
        storeName:"",
        storeCode:"",
        category:"2"
      },
      noticeParams:{
        type:""
      },
      exportParams:{
        category:""
      },
      sendDisabled:false,
      printDisabled:false,
      tableData:[],
      goodsSaleData:[],
      cabinetsNumTable:[],
      storeList:[],
      allStoreList:[],
      cabinetsList:[],
      userList:[],
      tableDataPt:[],
      menuList:[],
      cronList:[],
    })
    const methods = {
      clickCopy(msg) {
        const save = function(e) {
          e.clipboardData.setData('text/plain', msg)
          e.preventDefault() // 阻止默认行为
        }
        document.addEventListener('copy', save) // 添加一个copy事件
        document.execCommand('copy') // 执行copy方法
        this.$message({ message: '复制成功', type: 'success' })
      },
       getSummaries (param) {
        const { columns, data } = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '总计'
          }else if (index==2) {
            const values = data.map((item) => Number(item[column.property]))
            if (!values.every((value) => Number.isNaN(value))) {
              sums[index] = ` ${values.reduce((prev, curr) => {
                const value = Number(curr)
                if (!Number.isNaN(value)) {
                  return prev + curr
                } else {
                  return prev
                }
              }, 0)}`
            } else {
              sums[index] = 'N/A'
            }
          }else if(index==5){
            const values = data.map((item) => Number(item[column.property]))
            if (!values.every((value) => Number.isNaN(value))) {
              sums[index] = ` ${values.reduce((prev, curr) => {
                const value = Number(curr)
                if (!Number.isNaN(value)) {
                  return prev + curr
                } else {
                  return prev
                }
              }, 0)}`
            } 
          }else{
            sums[index] = '/'
          }
        })
        return sums
      },
      getSummaries1 (param) {
        const { columns, data } = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '总计'
          }else if (index==1) {
            const values = data.map((item) => Number(item[column.property]))
            if (!values.every((value) => Number.isNaN(value))) {
              sums[index] = ` ${values.reduce((prev, curr) => {
                const value = Number(curr)
                if (!Number.isNaN(value)) {
                  return prev + curr
                } else {
                  return prev
                }
              }, 0)}`
            } else {
              sums[index] = 'N/A'
            }
          }else{
            sums[index] = '/'
          }
        })
        return sums
      },
      // 发送短信通知
      async sendNotice(){
        if (!data.noticeParams.type) {
          ElMessage.error('请选择类型！！！')
          return
        }
        if (data.sendDisabled) {
          ElMessage.error('请勿频繁点击！！！')
          return
        }
        const res = await getSendData(data.noticeParams)
        if (res.code==0) {
          data.sendDisabled = true
          ElMessage.success('发送成功！')
          setTimeout(()=>{
            data.sendDisabled = false
          },60000)
        }else{
          ElMessage.error(res.message)
        }
      },
      // 获取保温柜订单数量
      async getCabinetsNum(){
        data.cabinetsNumTable.length=0
        const res = await getOrderData(data.cabinetsNumParams)
        if (res.code==0) {
          let tableData = []
          res.data.forEach(function (value) {
            let result = tableData.filter(function (item) {
              return item.cabinetName == value.cabinetName
            })[0]
            if (result) {
              // 说明已经存在过
              result.value += 1
            } else {
              tableData.push({ cabinetName: value.cabinetName, value: 1 })
            }
         })
         data.cabinetsNumTable.push(...tableData)
        }
      },

      refundClick(row){
        console.log(row,refundVisible.value);
        let form = {
          orderNo: row.orderNo,
          totalAmount: row.totalAmount,
          remark: '',
        }
        refundForm.value = {...form}
        refundVisible.value = true
      },
      // 退款
      async submitRefund(formEl){
        if (!formEl) return
        await formEl.validate((valid, fields) => {
          if (valid) {
            orderRefundData(refundForm.value).then(res=>{
              if (res.code==0 && res.data == '3') {
                ElMessage.success('退款成功！')
                refundVisible.value = false
                methods.getOrderList()
              }else
                ElMessage.error(res.message || '退款失败！')
            })
          } else {
            console.log('error submit!', fields)
          }
        })
      },
      // 取消退款
      cancelRefund(){
        refundVisible.value = false
      },

      // 获取订单列表
      async getOrderList(){
        if (!data.orderParams.storeCode) {
          ElMessage.error('请选择商铺！！！')
          return
        }
        data.tableData.length=0
        let param = JSON.parse(JSON.stringify(data.orderParams))
        if (param.type=='0') {
          param.type=""
        }
        const res = await getOrderData(param)
        if (res.code==0) {
          data.tableData.push(...res.data)
        }
      },
      // 获取拼团订单列表
      async getOrderListPt(){
        data.tableDataPt.length=0
        let param = {}
        const res = await getPtList(param)
        if (res.code==0) {
          data.tableDataPt.push(...res.data)
        }
      },
      // menuList
      async getMenuList(){
        data.menuList.length=0
        const res = await getMenuListData()
        if (res.code==0) {
          data.menuList.push(...res.data)
        }
      },
      // getCronList
      async getCronList(){
        data.cronList.length=0
        const res = await getCronListData()
        if (res.code==0) {
          data.cronList.push(...res.data)
        }
      },

      // 获取自提柜列表
      async getCabinetsList(){
        data.cabinetsList.length=0
        const res = await getCabinetData()
        if (res.code==0) {
          data.cabinetsList.push(...res.data.list)
        }
      },
      async getFeedbackData(){
        data.feedbackList.length = 0
        const res = await getFeedbackList()
        if (res.code==0) {
          res.data.forEach(item=>{
            if (item.imgs) {
              item.imgList = item.imgs.split(',')
            }else{
              item.imgList = []
            }
          })
          data.feedbackList.push(...res.data)
        }
      },
      async getGoodsData(){
        data.feedbackList.length = 0
        const res = await getGoodsList()
        if (res.code==0) {
          res.data.list.forEach(item=>{
            if (item.imgUrl) {
              item.imgList = item.imgUrl.split(',')
            }else{
              item.imgList = []
            }
          })
          data.goodsList.push(...res.data.list)
        }
      },
      async getPtGoodsData(){
        data.ptGoodsList.length = 0
        const res = await getPtGoodsList()
        if (res.code==0) {
          res.data.forEach(item=>{
            if (item.group.imgs) {
              item.group.imgList = item.group.imgs.split(',')
            }else{
              item.group.imgList = []
            }
            if (item.group.addressImg) {
              item.group.addressImgList = item.group.addressImg.split(',')
            }else{
              item.group.addressImgList = []
            }
          })
          data.ptGoodsList.push(...res.data)
        }
      },
      async getCategoryData(){
        data.categoryList.length = 0
        const res = await getCategoryList()
        if (res.code==0) {
          data.categoryList.push(...res.data.list)
        }
      },

      
      updatePassword(){
        dialogPassVisible.value = true
      },
      logout(){
        localStorage.removeItem('yxUserInfo')
        localStorage.removeItem('yxUserName')
        router.push('/login')
      },
      addUser(){
        dialogType.value = 'add'
        let form = {
          mobile:"",
          password:"",
          userType:"",
          storeCode:[],
          nickName:""
        }
        userForm.value = {...form}
        dialogFormVisible.value = true
      },
      editUser(row){
        let form = {
          mobile:row.userName,
          password:"",
          userType:row.userType,
          storeCode:row.storeCode.split(','),
          nickName:row.nickName,
        }
        userForm.value = {...form}
        dialogType.value = 'edit'
        dialogFormVisible.value = true
      },
      submitUpdatePass(formEl){
        if (!formEl) return
        formEl.validate((valid, fields) => {
          if (valid) {
            let param = passForm.value
            updatePasswordData(param).then(res=>{
              if (res.code==0) {
                ElMessage.success('修改成功！')
                dialogPassVisible.value = false
                methods.logout()
              }else{
                ElMessage.error(res.message)
              }
            })
          } else {
            console.log('error submit!', fields)
          }
        })
      },

      async submitAddUser (formEl) {
        if (!formEl) return
        await formEl.validate((valid, fields) => {
          if (valid) {
            let param = userForm.value
            param.storeCode = param.storeCode.join(',')
            addUserData(param).then(res=>{
              if (res.code==0) {
                ElMessage.success('操作成功！')
                dialogFormVisible.value = false
                methods.getUser()
              }else{
                ElMessage.error(res.message)
              }
            })
          } else {
            console.log('error submit!', fields)
          }
        })
      },

      // 获取商铺列表
      async getStoreData(){
        data.storeList.length=0
        data.allStoreList.length=0
        const res = await getStoreData()
        if (res.code==0) {
          data.allStoreList.push(...res.data)
          let codes = data.userInfo.code.split(',')
          res.data.forEach(val=>{
            if (codes.includes(val.code)) {
              data.storeList.push(val)
            }
          })
          data.orderParams.storeCode = data.storeList[0].code
          data.goodsParams.storeCode = data.storeList[0].code
          sharingRatio.value = data.storeList[0].sharingRatio
          methods.getOrderList()
        }
      },
      // 获取菜品销量
      async getGoodsList(){
        sharingRatio.value = data.allStoreList.find(item=>item.code==data.goodsParams.storeCode).sharingRatio
        console.log(787,sharingRatio.value);
        data.goodsSaleData.length=0
        const res = await getGoodsData(data.goodsParams)
        if (res.code==0 && res.data ) {
          let total1 = 0
          res.data.forEach(val=>{
            val.sales = Number(val.sales)
            total1+= Number(val.amount)
          })
          total.value = total1
          data.goodsSaleData.push(...res.data)
        }
      },
      // 获取用户列表
      async getUser(){
        data.userList.length=0
        const res = await getUserList()
        if (res.code==0 && res.data ) {
          data.userList.push(...res.data)
        }
      },
      // 导出菜品销量表格
      async exportGoodsList(){
        const res = await getGoodsExport(data.goodsParams)
        const link = document.createElement('a')
        let blob = new Blob([res])
        link.style.display = 'none'
        link.href = URL.createObjectURL(blob)
        link.download = data.goodsParams.date + '菜品销量.xlsx' //下载的文件名
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      },
      // 导出取件码
      async exportCodeFn(){
        if (!data.exportParams.category) {
          ElMessage.error('请选择类型！！！')
          return
        }
        const res = await exportCode(data.exportParams)
        let text = ""
        if (data.exportParams.category=='1') {
          text = "早餐"
        }else if (data.exportParams.category=='2') {
          text = "午餐"
        }else if (data.exportParams.category=='3') {
          text = "晚餐"
        }
        const link = document.createElement('a')
        let blob = new Blob([res])
        link.style.display = 'none'
        link.href = URL.createObjectURL(blob)
        let date = new Date()
        link.download = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' - '+text+'订单.xlsx' //下载的文件名
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      },
      // 切换tab
      onTabChange(tabName){
        if (tabName=='goods') {
          methods.getGoodsList()
        } else if(tabName=='order') {
          methods.getOrderList()
        }else if (tabName=='cabinets') {
          methods.getCabinetsNum()
        }else if (tabName=='user') {
          methods.getUser()
        }else if (tabName=='feedback') {
          methods.getFeedbackData()
        }else if (tabName=='goodsList') {
          methods.getGoodsData()
          methods.getCategoryData()
        }else if (tabName=='ptGoodsList') {
          methods.getPtGoodsData()
        }else if(tabName=='ptOrder'){
          methods.getPtGoodsData()
          methods.getOrderListPt()
        }else if (tabName=='weekMenu') {
          methods.getGoodsData()
          methods.getMenuList()
        }else if (tabName=='cron') {
          methods.getCronList()
        }
      },
      // 获取当前时间
      getNowFormatDate() {
        let date = new Date(),
          year = date.getFullYear(), //获取完整的年份(4位)
          month = date.getMonth() + 1, //获取当前月份(0-11,0代表1月)
          strDate = date.getDate() // 获取当前日(1-31)
        if (month < 10) month = `0${month}` // 如果月份是个位数，在前面补0
        if (strDate < 10) strDate = `0${strDate}` // 如果日是个位数，在前面补0
        return `${year}-${month}-${strDate}`
      },
      
      // 导出订单列表表格
      async exportTable(){
        const res = await getOrderExport(data.orderParams)
        const link = document.createElement('a')
        let blob = new Blob([res])
        link.style.display = 'none'
        link.href = URL.createObjectURL(blob)
        link.download = orderTypeText.value + '-' + data.orderParams.date+'订单列表.xlsx' //下载的文件名
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      },
      getStore(code){
        let codes = code.split(',')
        let strArr = []
        data.storeList.forEach(val=>{
          if (codes.includes(val.code)) {
            strArr.push(val.name)
          }
        })
        let str = strArr.join('、')
        return str
      },
      printTable(){
        let param = {}
        let confirmText = ""
        if (data.orderParams.storeCode) {
          let arr = data.storeList.filter(val=>{
            return val.code == data.orderParams.storeCode
          })
          param = {
            category:data.orderParams.category,
            storeCode:data.orderParams.storeCode,
            deviceSn:arr[0].printerSn
          }
          confirmText =  '确定要打印'+arr[0].name + '商铺下的订单么?'
        }else{
          ElMessage.error( '请选择商铺！')
          return
        }

        if (data.orderParams.cabinetName) {
          let cabinets = data.cabinetsList.filter(val=>{
            return val.name == data.orderParams.cabinetName
          })
          param.cabinetId = cabinets[0].id
        }
        ElMessageBox.confirm(confirmText,{
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(async () => {
          let res = await printCode(param)
          if (res.code==0) {
            ElMessage.success('打印成功！')
          }else{
            ElMessage.error( res.message || '打印失败！')
          }
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '取消打印',
          })
        })
      },
    }
    onMounted(()=>{
      data.goodsParams.date = methods.getNowFormatDate()
      data.orderParams.date = methods.getNowFormatDate()
      data.cabinetsNumParams.date = methods.getNowFormatDate()
      methods.getStoreData()
      methods.getCabinetsList()
    })
    // 计算属性
    const orderTypeText = computed(()=>{
      let typeText = ''
      switch (data.orderParams.type) {
        case '1':
          typeText = '保温柜订单'
          break;
        case '2':
          typeText = '自取订单'
          break;
        default:
          break;
      }
      return typeText
    })
    return {
      total,
      sharingRatio,
      dialogFormVisible,
      dialogPassVisible,
      refundVisible,
      passForm,
      userForm,
      refundForm,
      ruleFormRef,
      rulePassRef,
      ruleRefundRef,
      dialogType,
      ...data,
      ...methods,
    };
  },
};
</script>

<style lang="less" scoped>
/* Add your styles here */
.home{
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
  .user{
    position: absolute;
    top: 10px;
    right: 10px;
    z-index: 9;
    cursor: pointer;
  }
  // 适应手机
  @media (width <= 600px) {
    /deep/ .el-dialog {
      width: 80% !important;
    }
    .user{
      position: absolute;
      top: 40px;
    }
  }
  :deep(.el-tabs__content){
    flex: 1;
  }
  .el-tab-pane{
    display: flex;
    height: 100%;
    flex-direction: column;
  }
  .el-tabs--border-card{
    flex-direction: column;
    height: 100%;
    border: none !important;
    display: flex;
  }
  .search{
    width: 100%;
    display: flex;
    align-items: center;
    padding: 10px 20px 0 20px;
    box-sizing: border-box
  }
  .add{
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    padding: 10px;
    box-sizing: border-box
  }
  .table{
    flex: 1;
    overflow-y: auto;
  }
  .orderTable{
    :deep(tbody) tr:hover>td {
      background: none;
    }
    :deep(.el-table__row){
      background: #EEF5FE;
    }
    :deep(.expandTable) .el-table__row{
      background: #FFFFFF;
    }
  }
}
</style>